#include "stdlib.hpp"

#include <purewell/purewell.hpp>
#include <purewell/types.hpp>
#include <purewell/system.hpp>

namespace purewell
{

PWSystem& gPWSystem(PWSystem::getInstance());

PWSystem::PWSystem()
{
}

PWSystem&
PWSystem::getInstance(void)
{
	static PWSystem sys;
	return sys;
}

char*
PWSystem::getCurrentDirectory(char* buf, size_t blen) const
{
	return getcwd(buf,blen);
}

std::string&
PWSystem::getCurrentDirectory(std::string& out) const
{
	out.clear();

	char* buf(NULL);
	size_t blen(1024);
	int eno(0);

	do
	{
		if ( NULL == (buf = (char*)malloc(blen)) )
		{
			break;
		}

		errno = 0;
		if ( NULL != getcwd(buf, blen) )
		{
			buf[blen-1] = 0x00;
			out = buf;
			free(buf);
			break;
		}
		eno = errno;

		free(buf);

		if ( eno != ERANGE )
		{
			break;
		}

		blen *= 2;

	} while (true);

	return out;
}

std::ostream*
PWSystem::setLibraryLogStream(std::ostream* os) const
{
	return gLibLog.setStream(os);
}

std::ostream*
PWSystem::getLibraryLogStream(void) const
{
	return gLibLog.getStream();
}

void
PWSystem::getLibraryVersion(int* major, int* minor,
	int* patch, int* rel) const
{
	if ( major )
	{
		*major = PWVER_MAJOR;
	}

	if ( minor )
	{
		*minor = PWVER_MINOR;
	}

	if ( patch )
	{
		*patch = PWVER_PATCH;
	}

	if ( rel )
	{
		*rel = PWVER_RELEASE;
	}
}

};//namespace purewell

